package com.example.home7.server;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

import com.example.home7.R;

public class MuSicAid {
    private MediaPlayer mediaPlayer;
    private final int[] musicResource = new int[]{R.raw.second,R.raw.first};
    private boolean prepared = false;
    private int currentMusicIndex = 0;
    private Context context;
    public MuSicAid(Context context) {
        this.context = context;
        createPlayer();
    }
    private void createPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }
    public void begin() {
        if(mediaPlayer.isPlaying()) return;
        if(prepared) {
            mediaPlayer.start();
            return;
        }
        try {
            mediaPlayer.setDataSource(context, Uri.parse("android.resource://com.example.home7/"
                    + musicResource[currentMusicIndex]));
        } catch (Exception e) {
            e.printStackTrace();
        }
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                prepared = true;
            }
        });
    }
    public void pause() {
        if(!mediaPlayer.isPlaying()) return;
        mediaPlayer.pause();
    }

    public void next() {
        currentMusicIndex = (currentMusicIndex+1) % musicResource.length;
        destroy();
        createPlayer();
        begin();
    }

    public void destroy() {
        if(mediaPlayer == null) return;
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        prepared = false;
    }
}
